import Vue from 'vue'
import Router from 'vue-router'

import Login from "../components/Login";
import Home from "../components/Home";
import ProdList from "../components/comps/ProdList";
import ProdDetails from "../components/comps/ProdDetails";
import {getToken} from "../util/auth";
import Cart from "../components/comps/Cart";
import Order from "../components/comps/Order";
import Customer from "../components/comps/Customer";
import Shipping from "../components/comps/Shipping";
import OrderCreating from "../components/comps/OrderCreating";
import Payment from "../components/comps/Payment";

Vue.use(Router)



const router = new Router({
  routes: [

    {
      path:'/',
      redirect:'/home'
    },

    //首页路由
    {
      path:'/home',
      name:'Home',
      component:Home,
      redirect:'/prod/list',
      children:[
        {
          path:'/prod/list',
          name:'ProdList',
          component:ProdList
        },
        {
          path:'/prod/details/:id',
          name:'ProdDetails',
          component:ProdDetails
        },
        {
          path:'/cart',
          name:'Cart',
          component:Cart
        },
        {
          path: '/order',
          name:'Order',
          component:Order
        },
        {
          path: '/payment/:id',
          name:'Payment',
          component:Payment
        },
        {
          path:'/customer',
          name:'Customer',
          component:Customer,
          redirect:'/shipping',
          children:[
            {
              path:'/shipping',
              name:'Shipping',
              component:Shipping
            }
          ]
        },
        {
          path:'/order/creating',
          name:'OrderCreating',
          component: OrderCreating
        }
      ]
    },

    //登录页路由
    {
      path:'/login',
      name:"Login",
      component:Login
    }
  ]
})

//路由导般守卫
router.beforeEach((to,from,next)=>{
  const token = getToken();
  //如果目标是登录路由，则直接放行
  if(to.path == '/login'){

    if(token){
      return next('/home');
    }else{
      return next();
    }

  }else {
    console.log("token="+token);
    //否则根据token是否存在来拦载
    //获取token
    if (token) {
      return next();
    } else {
      next('/login');
    }
  }
});

export default  router;
